package com.program.facesigninsystem.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanDescriptionFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.program.facesigninsystem.iteration.entity.SigninactivityEntity;
import com.program.facesigninsystem.iteration.entity.SigninclassEntity;
import com.program.facesigninsystem.iteration.entity.SigninlinkEntity;
import com.program.facesigninsystem.iteration.entity.UserSigninclassEntity;
import com.program.facesigninsystem.iteration.mapper.SigninactivityMapper;
import com.program.facesigninsystem.iteration.mapper.SigninclassMapper;
import com.program.facesigninsystem.iteration.mapper.SigninlinkMapper;
import com.program.facesigninsystem.iteration.mapper.UserSigninclassMapper;
import com.program.facesigninsystem.service.SignInClassService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

@Slf4j
@Service
public class SignInClassServiceImpl implements SignInClassService {

    @Resource
    SigninclassMapper signinclassMapper;
    @Resource
    UserSigninclassMapper userSigninclassMapper;
    @Resource
    SigninactivityMapper signinactivityMapper;
    @Resource
    SigninlinkMapper signinlinkMapper;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    SignInActivityService signInActivityService;

    @Override
    public Boolean excelImport(MultipartFile file, String listName, String uid) {
        // 开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            Workbook wb = WorkbookFactory.create(file.getInputStream());
            // 操作第一个sheet
            Sheet sheet = wb.getSheetAt(0);

            Row row = sheet.getRow(0);
            int columnSize = row.getLastCellNum();
            int nameList = -1;
            int numberlist = -1;
            for (int c = 0; c < columnSize; c++) {
                if (row.getCell(c).getStringCellValue().equals("姓名")) {
                    nameList = c;
                }
                if (row.getCell(c).getStringCellValue().equals("学号")) {
                    numberlist = c;
                }
            }
            if (nameList == -1) throw new Exception("Excel格式错误！");

            int number = 0;

            SigninclassEntity signinclassEntity = new SigninclassEntity();
            signinclassEntity.setName(listName)
                    .setNumber(0)
                    .setUid(uid);
            signinclassMapper.insert(signinclassEntity);

            // 开始操作
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                row = sheet.getRow(r);
                row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                if (row.getCell(0).getStringCellValue().trim().equals("")) {
                    break;
                }
                String signinnumber = "";
                String studentId = "";
                row.getCell(nameList).setCellType(Cell.CELL_TYPE_STRING);
                String name = row.getCell(nameList).getStringCellValue();
                if (numberlist != -1) {
                    row.getCell(numberlist).setCellType(Cell.CELL_TYPE_STRING);
                    signinnumber = row.getCell(numberlist).getStringCellValue();
                    studentId = signinnumber;  // 假设“学号”就是 studentId
                }
                number++;

                UserSigninclassEntity userSigninclassEntity = new UserSigninclassEntity();
                userSigninclassEntity.setName(name)
                        .setSigninclassId(signinclassEntity.getId())
                        .setSigninclassNumber(signinnumber)
                        .setStudentId(studentId);  // 设置 studentId

                userSigninclassMapper.insert(userSigninclassEntity);
            }

            signinclassEntity.setNumber(number);
            signinclassMapper.updateById(signinclassEntity);

            // 提交事务
            platformTransactionManager.commit(status);
            return true;

        } catch (Exception e) {
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }


    @Override
    public List<SigninclassEntity> getList(String uid, int pageNum, int pageSize) {

        //分页
        PageHelper.startPage(pageNum, pageSize);
        return signinclassMapper.selectList(new QueryWrapper<SigninclassEntity>().eq("uid", uid));
    }

    @Override
    public List<SigninclassEntity> getList2(String uid) {

        return signinclassMapper.selectList(new QueryWrapper<SigninclassEntity>().eq("uid", uid));
    }

    @Override
    public Boolean updateSigninClass(int listId, String listName) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            SigninclassEntity signinclassEntity = signinclassMapper.selectById(listId);
            signinclassEntity.setName(listName);
            signinclassMapper.updateById(signinclassEntity);

            //提交事务
            platformTransactionManager.commit(status);
            return true;

        } catch (Exception e) {
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }

    @Override
    public List<UserSigninclassEntity> getMember(int listId) {

        return userSigninclassMapper.selectList(new QueryWrapper<UserSigninclassEntity>().eq("signinclass_id", listId));
    }

    @Override
    public Boolean delList(int listId) {

        return signinclassMapper.deleteById(listId) == 1;
    }

    @Override
    public Boolean delMembers(int listId, String[] names,String[] signinclass_number) {

        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            for (String name : names) {
                if(signinclass_number ==null) {
                    userSigninclassMapper.delete(new QueryWrapper<UserSigninclassEntity>()
                            .eq("name", name)
                            .eq("signinclass_id", listId));
                }else {
                    userSigninclassMapper.delete(new QueryWrapper<UserSigninclassEntity>()
                            .eq("name", name)
                            .eq("signinclass_id", listId)
                            .eq("signinclass_number",signinclass_number));
                }
            }
            SigninclassEntity signinclassEntity = signinclassMapper.selectById(listId);
            signinclassEntity.setNumber(signinclassEntity.getNumber() - names.length);
            signinclassMapper.updateById(signinclassEntity);
            //提交事务
            platformTransactionManager.commit(status);
            return true;

        } catch (Exception e) {
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }

    @Override
    public Boolean insertMembersExcel(MultipartFile file, int listId) {
        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            Workbook wb = WorkbookFactory.create(file.getInputStream());
            // 操作第一个sheet
            Sheet sheet = wb.getSheetAt(0);

            Row row = sheet.getRow(0);
            int columnSize = row.getLastCellNum();
            int nameList = -1;
            int numberlist = -1;
            for (int c = 0; c < columnSize; c++) {
                if (row.getCell(c).getStringCellValue().equals("姓名")) {
                    nameList = c;
                }
                if (row.getCell(c).getStringCellValue().equals("学号")) {
                    numberlist = c;
                }
            }
            if (nameList == -1)
                throw new Exception("Excel格式错误！");

            int number = 0;

            SigninclassEntity signinclassEntity = signinclassMapper.selectById(listId);

            //开始操作
            for (int r = 1; r <= sheet.getLastRowNum(); r++) {
                row = sheet.getRow(r);
                row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);  // 使用 CELL_TYPE_STRING
                if (row.getCell(0).getStringCellValue().trim().equals("")) {
                    break;
                }
                String signin_number = "";

                row.getCell(nameList).setCellType(Cell.CELL_TYPE_STRING); // 使用 CELL_TYPE_STRING
                String name = row.getCell(nameList).getStringCellValue();

                // 判断"学号"列的单元格类型
                if (numberlist != -1) {
                    Cell cell = row.getCell(numberlist);
                    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {  // 使用 CELL_TYPE_NUMERIC
                        // 如果是数字类型，将其转化为字符串
                        signin_number = String.valueOf((long) cell.getNumericCellValue());
                    } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {  // 使用 CELL_TYPE_STRING
                        // 如果是字符串类型，直接获取字符串值
                        signin_number = cell.getStringCellValue();
                    }
                }
                number++;

                UserSigninclassEntity userSigninclassEntity = new UserSigninclassEntity();
                // 设置姓名、学号和签到名单ID
                userSigninclassEntity.setName(name)
                        .setSigninclassNumber(signin_number) // 学号赋值给 signinclass_number
                        .setSigninclassId(signinclassEntity.getId())
                        .setStudentId(signin_number); // 学号赋值给 student_id

                // 插入到数据库
                userSigninclassMapper.insert(userSigninclassEntity);
            }

            signinclassEntity.setNumber(signinclassEntity.getNumber() + number);
            signinclassMapper.updateById(signinclassEntity);

            // 提交事务
            platformTransactionManager.commit(status);
            return true;

        } catch (Exception e) {
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }



    @Override
    public Boolean insertMembersManual(int listId, String name, String studentId, String sign_number) {

        if (sign_number == null){
            sign_number = "";
        }
        //开启事务
        TransactionStatus status = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            UserSigninclassEntity userSigninclassEntity = new UserSigninclassEntity();
            userSigninclassEntity.setName(name)
                    .setStudentId(studentId)
                    .setSigninclassNumber(sign_number)
                    .setSigninclassId(listId);
            userSigninclassMapper.insert(userSigninclassEntity);

            SigninclassEntity signinclassEntity = signinclassMapper.selectById(listId);
            signinclassEntity.setNumber(signinclassEntity.getNumber() + 1);
            signinclassMapper.updateById(signinclassEntity);
            //提交事务
            platformTransactionManager.commit(status);
            return true;

        } catch (Exception e) {
            log.info(e.getMessage());
            platformTransactionManager.rollback(status);
            return false;
        }
    }

    @Override
    public SigninclassEntity selectClassbylid(String lid) {
        QueryWrapper<SigninlinkEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("lid",lid);
        SigninlinkEntity signinlinkEntity = signinlinkMapper.selectOne(queryWrapper);
        String actid = signinlinkEntity.getActid();
        String cid = signinactivityMapper.selectOne(new QueryWrapper<SigninactivityEntity>().eq("actid",actid)).getCid();
        return signinclassMapper.selectOne(new QueryWrapper<SigninclassEntity>().eq("id", cid));
    }

    @Override
    public UserSigninclassEntity selectUserSigninClassbylid(String lid) {
        QueryWrapper<SigninlinkEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("lid",lid);
        SigninlinkEntity signinlinkEntity = signinlinkMapper.selectOne(queryWrapper);
        String actid = signinlinkEntity.getActid();
        String cid = signinactivityMapper.selectOne(new QueryWrapper<SigninactivityEntity>().eq("actid",actid)).getCid();
        return userSigninclassMapper.selectOne(new QueryWrapper<UserSigninclassEntity>().eq("id", cid));
    }
}
